export default class Map {
  constructor(opts) {
    //获取页面实例，方便调用方法
    this.vueInstance = opts.vueInstance;
    this.$el = opts.el || 'map'
    //获取不同地图构造函数
    this.isBaidu = opts.type === "baidu";
    this.mapConstructor = this.isBaidu ? window.BMap : window.AMap;
    this.paintType = opts.type;
    this.showTraffic = opts.showTraffic;
    this.getCurrentMapType(opts.mapType);
    this.map = null;
    this.init();
    this.oldTraffic = null;
    this.toggleTrafficStatus();
  }

  //获取不同地图类型变量
  getCurrentMapType(mapType) {
    let normalMap = this.isBaidu
      ? BMAP_NORMAL_MAP
      : new AMap.createDefaultLayer();
    let saliteMap = this.isBaidu
      ? BMAP_SATELLITE_MAP
      : new AMap.TileLayer.Satellite();
    this.mapType = mapType === "normal" ? normalMap : saliteMap;
  }

  //改变地图类型
  changeMapType(mapType) {
    this.getCurrentMapType(mapType);
    let setMapTypeMethod = this.isBaidu ? "setMapType" : "setLayers";
    let layer = this.isBaidu ? this.mapType : [this.mapType]; //兼容两种不同的数据格式
    this.map[setMapTypeMethod](layer);
  }

  //改变showTraffic
  toggleTrafficValue(bool) {
    this.showTraffic = bool;
    this.toggleTrafficStatus();
  }

  //切换路况
  toggleTrafficStatus() {
    if (this.showTraffic) {
      //取名为oldTraffic只是为了少添加一个变量
      this.oldTraffic = this.isBaidu
        ? new BMap.TrafficLayer()
        : new AMap.TileLayer.Traffic();
      let addTrafficeMethod = this.isBaidu ? "addTileLayer" : "addLayer";
      this.map[addTrafficeMethod](this.oldTraffic);
    } else {
      let RemoveTrafficeMethod = this.isBaidu
        ? "removeTileLayer"
        : "removeLayer";
      this.map[RemoveTrafficeMethod](this.oldTraffic);
    }
  }

  //测量距离
  testDistance() {
    if (this.isBaidu) {
      var DistanceTool = new BMapLib.DistanceTool(this.map, { lineStroke: 2 });
      DistanceTool.open();
    } else {
      this.map.plugin(["AMap.MouseTool"], () => {
        let ruler = new AMap.RangingTool(this.map);
        ruler.turnOn()
        ruler.on('end', () => {
          ruler.turnOff()
        })
      });
    }
  }

  //高德经纬度转百度
  GaodeLngLatToBaidu(lng, lat) {
    let x_pi = (3.14159265358979324 * 3000.0) / 180.0;
    let x = lng;
    let y = lat;
    let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
    let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
    let lngs = z * Math.cos(theta) + 0.0065;
    let lats = z * Math.sin(theta) + 0.006;

    return {
      lng: lngs,
      lat: lats
    };
  }

  //百度经纬度转高德
  BaiduLngLatToGaode(lng, lat) {
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = lng - 0.0065;
    let y = lat - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let lngs = z * Math.cos(theta);
    let lats = z * Math.sin(theta);
    
    return {
        lng: lngs,
        lat: lats        
    }   
}
}
